package org.nofs.database;

import lombok.Getter;
import org.nofs.Grasscutter;
import org.nofs.config.Configuration;
import org.nofs.game.Account;

/* loaded from: sdkserver.jar:emu/grasscutter/database/DatabaseManager.class */

import java.sql.*;

public class DatabaseManager {

    @Getter
    private static Connection connection;


//    public static void initialize() {
//        try {
//            // Load the MySQL JDBC driver
//            Class.forName("com.mysql.jdbc.Driver");
//            // Establish a connection to MySQL
//            connection = DriverManager.getConnection(Configuration.DATABASE.server.connectionUri, Configuration.DATABASE.server.username, Configuration.DATABASE.server.password);
//            //Grasscutter.getLogger().info("Connected to mysql database successful.");
//        } catch (Exception e) {
//            Grasscutter.getLogger().error("Database connection error: ", e);
//        }
//    }

    public static void createDatabase() throws SQLException, ClassNotFoundException {
        // Load the MySQL JDBC driver
        Class.forName("com.mysql.jdbc.Driver");
        // Establish a connection to MySQL
        String host = Configuration.DATABASE.server.connectionUri;
        String database_name = Configuration.DATABASE.server.database_name;
        String username = Configuration.DATABASE.server.username;
        String password = Configuration.DATABASE.server.password;
        String str = Configuration.DATABASE.server.str;
        connection = DriverManager.getConnection(host, username, password);
        Statement statement = connection.createStatement();
        String createDatabaseSql = "CREATE DATABASE IF NOT EXISTS " + database_name;
        statement.executeUpdate(createDatabaseSql);
        statement.close();
    }


    public static void initialize() {
        try {
            // Load the MySQL JDBC driver
            Class.forName("com.mysql.jdbc.Driver");
            // Establish a connection to MySQL
            String host = Configuration.DATABASE.server.connectionUri;
            String database_name = Configuration.DATABASE.server.database_name;
            String username = Configuration.DATABASE.server.username;
            String password = Configuration.DATABASE.server.password;
            String str = Configuration.DATABASE.server.str;
            connection = DriverManager.getConnection(host + database_name + str, username, password);
            // Check if the 'accounts' table exists
            if (!isTableExists("accounts")) {
                createTable();
            }
            //Grasscutter.getLogger().info("Connected to mysql database successful.");
        } catch (Exception e) {
            Grasscutter.getLogger().error("Database connection error: ", e);
        }
    }

    public static boolean isTableExists(String tableName) {
        try (ResultSet rs = connection.getMetaData().getTables(null, null, tableName, null)) {
            return rs.next();
        } catch (SQLException e) {
            Grasscutter.getLogger().error("Error checking if table exists: ", e);
            return false;
        }
    }

    public static void createTable() {
        String query = "CREATE TABLE accounts ("
                + "id INT(36) PRIMARY KEY,"
                + "username VARCHAR(255) UNIQUE NOT NULL,"
                + "password VARCHAR(255) NOT NULL,"
                + "reservedPlayerId INT,"
                + "email VARCHAR(255),"
                + "token VARCHAR(255),"
                + "sessionKey VARCHAR(255)"
                + ")";
        try (Statement stmt = connection.createStatement()) {
            stmt.executeUpdate(query);
            Grasscutter.getLogger().info("Created 'accounts' table");
        } catch (SQLException e) {
            Grasscutter.getLogger().error("Error creating table: ", e);
        }
    }

//    public static synchronized int getNextId(String id) {
//        String sql = "INSERT INTO accounts (id) VALUES (?) ON DUPLICATE KEY UPDATE count = count + 1";
//        int nextId = -1;
//
//        try (PreparedStatement stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
//            stmt.setString(1, id);
//            int affectedRows = stmt.executeUpdate();
//
//            if (affectedRows == 0) {
//                throw new SQLException("Creating counter failed, no rows affected.");
//            }
//
//            try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
//                if (generatedKeys.next()) {
//                    nextId = generatedKeys.getInt(1);
//                } else {
//                    throw new SQLException("Creating counter failed, no ID obtained.");
//                }
//            }
//
//        } catch (SQLException e) {
//            Grasscutter.getLogger().error("Error retrieving next ID for counter " + id + ": ", e);
//        }
//
//        return nextId;
//    }

    public static synchronized int getNextId(String tableName) {
        String sql = "SELECT id FROM " + tableName + " ORDER BY id DESC LIMIT 1";
        int lastId = -1;

        try (PreparedStatement stmt = connection.prepareStatement(sql);
             ResultSet resultSet = stmt.executeQuery()) {

            if (resultSet.next()) {
                lastId = resultSet.getInt("id");
            }

        } catch (SQLException e) {
            Grasscutter.getLogger().error("Error retrieving last ID for table " + tableName + ": ", e);
        }

        return lastId;
    }
}

//public final class DatabaseManager {
//    private static Datastore dispatchDatastore;
//
//    public static Datastore getAccountDatastore() {
//        return dispatchDatastore;
//    }
//
//    public static void initialize() {
//        MapperOptions mapperOptions = MapperOptions.builder().storeEmpties(true).storeNulls(false).build();
//        MongoClient dispatchMongoClient = MongoClients.create(Configuration.DATABASE.server.connectionUri);
//        dispatchDatastore = Morphia.createDatastore(dispatchMongoClient, Configuration.DATABASE.server.collection, mapperOptions);
//        dispatchDatastore.getMapper().map(DatabaseCounter.class, Account.class);
//        ensureIndexes(dispatchDatastore);
//    }
//
//    private static void ensureIndexes(Datastore datastore) {
//        try {
//            datastore.ensureIndexes();
//        } catch (MongoCommandException e) {
//            Grasscutter.getLogger().info("Mongo index error: ", (Throwable) e);
//            if (e.getCode() == 85) {
//                MongoIterable<String> collections = datastore.getDatabase().listCollectionNames();
//                MongoCursor<String> it2 = collections.iterator();
//                while (it2.hasNext()) {
//                    String name = it2.next();
//                    datastore.getDatabase().getCollection(name).dropIndexes();
//                }
//                datastore.ensureIndexes();
//            }
//        }
//    }
//
//    public static synchronized int getNextId(Class<?> c) {
//        DatabaseCounter counter = (DatabaseCounter) getAccountDatastore().find(DatabaseCounter.class).filter(Filters.eq(DBCollection.ID_FIELD_NAME, c.getSimpleName())).first();
//        if (counter == null) {
//            counter = new DatabaseCounter(c.getSimpleName());
//        }
//        try {
//            int nextId = counter.getNextId();
//            getAccountDatastore().save(counter);
//            return nextId;
//        } catch (Throwable th) {
//            getAccountDatastore().save(counter);
//            throw th;
//        }
//    }
//
//    public static synchronized int getNextId(Object o) {
//        return getNextId(o.getClass());
//    }
//}
